<template>
	<div id="privateLette">
		<div class="i_maxW">
			<div class="u_crumbs">
				<router-link to="/personal/index">个人中心</router-link>
				<strong>
					<i>></i>私信
				</strong>
			</div>
			<!--  -->
			<div class="u_content privateLetteBox">
				<div class="content_l box">
					<div class="communicationBox">
						<div class="communication">
							<router-link to="/personal/contact/privateLette">私信</router-link>
							<router-link to="/personal/contact/mailList">通讯录</router-link>
						</div>
						<div class="communication_c" v-if="userChatList.length">
							<el-scrollbar>
								<div class="userGroup userGroup2" v-for="item in userChatList" :key=" item.id">
									<label>
										<span @click="deleteUserChat(item.send_id)">
											<i class="el-icon-close"></i>
										</span>
										<input type="radio" name="group" :checked="item.send_id == currentUserId">
										<div class="userGroup_txt" :class="{ activeChat: isActive }" @click="getUserChatOne(item.send_id)">
											<i class="tips box" v-if="item.read_data == '未读'"></i>
											<div class="box">
												<img v-if="item.avatar_path !== ''" :src="BASE_URL+item.avatar_path">
												<img v-else src="../../../public/images/Group9.png">
											</div>
											<div class="box">
												<p>{{ item.username }}</p>
												<p v-html="emoji(item.content)"></p>
											</div>
										</div>
									</label>
								</div>
							</el-scrollbar>
						</div>
						<!--  -->
						<div class="usetInfo_cb" v-else>
							<span>- 暂无私信 -</span>
						</div>
					</div>
				</div>
				<!--  -->
				<div class="content_r box  ">
					<div class="usetInfo" v-show="currentUserId">
						<div class="u_chat" id="chats">
							<vue-scrollbar class="my-scrollbar" ref="Scrollbar">
								<ul id="chat_record">
									<li :class="['chatCont', { is_active: item.send_id == $g.user_id }]" v-for="item in userChatMessage" :key="item.id">
										<div class="chatCont_txt clear">
											<span class="chatCont_g box fl">
												<img v-if="item.send_avatar_path !== ''" :src="BASE_URL+item.send_avatar_path">
												<img v-else src="../../../public/images/Group9.png">
											</span>
											<div class="chatCont_bx clear">
												<template v-if="item.type===0">
													<div class="chatCont_t box" v-html="emoji(item.app_content)"></div>
												</template>
												<template v-else-if="item.type===1">
													<div class="chatCont_t box">
														<el-image class="talk-img" :src="BASE_URL+item.app_content" :preview-src-list="[BASE_URL+item.app_content]"></el-image>
													</div>
												</template>
												<template v-else-if="item.type===2">
													<div class="chatCont_t box"><i class="el-icon-chat-dot-round"></i>此内容为音频，请在移动端播放</div>
												</template>
												<span class="dataTime">{{getDateDiff(item.create_time)}}</span>
											</div>
										</div>
									</li>
								</ul>
							</vue-scrollbar>
						</div>
						<div class="l_chat">
							<div id="content" class="txt-content"></div>
							<div class="msg-btn">
								<el-button type="primary" @click="sendMessage()" v-preventReClick>发送</el-button>
							</div>
						</div>
					</div>
					<!-- 无数据状态 -->
					<div class="user_bgx" v-show="!currentUserId">
						<i class="ipm slogn02"></i>
						<img src="../../../public/images/tongxunlu_image01.png">
					</div>
				</div>
			</div>
		</div>
	</div>
</template>
<script>
	import VueScrollbar from 'vue2-scrollbar';
require("vue2-scrollbar/dist/style/vue2-scrollbar.css")

import E from 'wangeditor'; 
import emotions from '../../../public/emotions.json'
let btnmenu = [
   // 'bold',//粗体
   // 'fontSize',//字号
   // 'fontName',//字体
   // 'italic',//斜体
   // 'undeline',//下划线
   // 'justify',//对齐方式
   // 'quote',//引用
  'emoticon',//表情
  'link',//插入链接
  // 'strikeThrough',//删除线
  'undo', //撤销
  'redo', // 重复
   ]


export default {
	name: 'privateLettes',
	components: {VueScrollbar},
	data() {
		return {
			activeNames: ['1'],
			chatInput: '',/*输入框*/
			userChatList: [],/*私信用户列表*/
			currentUserId: 0,/*选中的用户id*/
			userChatMessage: [],/*聊天记录列表*/
			temp_userChatList:null,
			path: null,
			ws: null,/*ws通讯*/
			isActive: false,/*选中用户的样式*/
			editor: null/*富文本*/
		}
	},
	mounted() {

		this.$nextTick(()=> {
	    	// 代码保证 this.$el 在 document 中

	   		this.editor = new E('#content');
			// 自定义菜单配置
			this.editor.customConfig.menus = btnmenu;
			this.editor.customConfig.debug = true
			// 设置超时
			this.editor.customConfig.uploadImgTimeout=3*60*1000;
			// 关闭粘贴样式的过滤
			this.editor.customConfig.pasteFilterStyle = false;
			// 忽略粘贴内容中的图片
			this.editor.customConfig.pasteIgnoreImg = true;
			this.editor.customConfig.onfocus = ()=>{
				// if (this.editor.txt.html() === '<p class="e-placeholder">写点什么···</p>') {
				// 	this.editor.txt.html('') 
				// }
				// 
			}

			this.editor.customConfig.onblur = (html)=>{

			}
			this.editor.customConfig.onchange = (html) => {
				this.chatInput = html
			}
			// 表情面板可以有多个 tab ，因此要配置成一个数组。数组每个元素代表一个 tab 的配置
			this.editor.customConfig.emotions = [
				{
					// tab 的标题
					title: '默认',
					type: 'image',
					content: emotions
				}
			]
			this.editor.create();
	    	this.getUserChatList()
			this.websocket()


			let titleArr= ['表情', '链接',  '撤销', '恢复']
			let iconArr = document.querySelectorAll('.w-e-menu i')
			iconArr.forEach((item, index)=>{
				item.parentNode.setAttribute('title', titleArr[index])
			})

	 	})
	},
	beforeDestroy() {
		this.over()
	},
	creared(){	
		
	},
	methods: {

		getDateTimeStamp (dateStr) {
		    return Date.parse(dateStr.replace(/-/gi,"/"));
		},
		/**
		 * 时间转换
		 * @DateTime 2020-03-05T13:47:47+0800
		 * @param    {[type]}                 dateStr [description]
		 * @return   {[type]}                         [description]
		 */
		getDateDiff (dateStr) {
		    var publishTime = this.getDateTimeStamp(dateStr)/1000,
		        Dseconds,
		        Dminutes,
		        Dhours,
		        Ddays,
		        timeNow = parseInt(new Date().getTime()/1000),
		        d,

		        date = new Date(publishTime*1000),
		        Y = date.getFullYear(),
		        M = date.getMonth() + 1,
		        D = date.getDate(),
		        H = date.getHours(),
		        m = date.getMinutes(),
		        s = date.getSeconds();
		        //小于10的在前面补0
		        if (M < 10) { M = '0' + M}
		        if (D < 10) { D = '0' + D}
		        if (H < 10) {H = '0' + H }
		        if (m < 10) {m = '0' + m }
		        if (s < 10) { s = '0' + s}

		    d = timeNow - publishTime;
		    Ddays = parseInt(d/86400);
		    Dhours = parseInt(d/3600);
		    Dminutes = parseInt(d/60);
		    Dseconds = parseInt(d);

		    if(Ddays > 0 && Ddays < 3){
		          return M + '-' + D + ' ' + H + ':' + m;
		    }else if(Ddays <= 0 && Dhours > 0){
		       return '昨天'+ ' ' + H + ':' + m;
		    }else if(Dhours <= 0 && Dminutes > 0){
		         return H + ':' + m;
		    }else if (Dseconds < 60) {
		    	return '刚刚';
		        if (Dseconds <= 0) {
		        	 return '';
		        }else {
		        	   return '';
		        }
		    }else if (Ddays >= 3 && Ddays < 30){
		        return M + '-' + D + ' ' + H + ':' + m;
		    }else if (Ddays >= 30) {
		        // return Y + '-' + M + '-' + D + ' ' + H + ':' + m;
		        return M + '-' + D + ' ' + H + ':' + m;
		    }
		},
		/**
		 * 滚动条，页面初始化时根据内容滚到底部
		 * @DateTime 2020-03-05T13:53:55+0800
		 * @return   {[type]}                 [description]
		 */
		someMethod() {

			this.$nextTick(()=>{
				if (this.currentUserId && document.getElementById('chat_record') ) {
					let h = document.getElementById('chat_record').clientHeight
					this.$refs.Scrollbar.scrollToY(h)
				}   
			})			   
		},
		/**
		 * 获取需要聊天的用户数据
		 * @DateTime 2020-03-05T13:55:51+0800
		 * @return   {[type]}                 [description]
		 */
		getUserChatList() {
			let success = (res => {		
				let _this = this
				this.userChatList = deep_clone(res.data);
				this.currentUserId = 0;
				this.temp_userChatList = this.$store.getters.send_userinfo


				// if (this.temp_userChatList.send_id === this.$g.user_id) {
				// 	console.info(this.temp_userChatList.send_id, this.$g.user_id)
				// 	this.$message.error('不能给自己发私信');
				// 	//this.$router.back(-1)
				// 	return
				// }

				if (this.temp_userChatList != null) {

					let flag = false;
					this.userChatList.forEach(function(item, i) {
						if (item.send_id == _this.temp_userChatList.send_id) {	
							return flag = true;
						}
					})

					!flag && this.userChatList.unshift({
						send_id : this.temp_userChatList.send_id,
						avatar_path : this.temp_userChatList.avatar_path,
						username:this.temp_userChatList.username
					});

					this.currentUserId = this.temp_userChatList.send_id;
					_this.getUserChatOne(this.currentUserId);
					let message = JSON.stringify({
						type: 'allread',
						send_id: this.currentUserId,
						receive_id:  this.$g.user_id
					})
					this.ws.send(message)
				}
			})

			let params = {
				user_id: this.$g.user_id
			}
			this.$ajax.get('api/user/user_chat_list', { params, func: { success: success} })

		},
		/**
		 * 是否要删除对话的用户（记录会清空）
		 * @DateTime 2020-03-05T14:04:35+0800
		 * @param    {[type]}                 id [description]
		 * @return   {[type]}                    [description]
		 */
		deleteUserChat(id) {
			this.$confirm('确定删除该对话吗?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
				customClass: 'confirm-them'
			}).then(() => {
				let success = (res => {		
					this.getUserChatList();
					if ( this.temp_userChatList !== null && this.temp_userChatList.send_id == this.$store.getters.send_userinfo.send_id){
						this.$store.commit('SET_SEND_USERINFO', null );
					}
				})
				
				this.$ajax({
					url: '/api/user/user_chat_list',
					method: 'delete',
					params: {
						user_id: this.$g.user_id,
						otheruserid: id
					},
					func:{success:success}
				})
			}).catch(() => {});
			return false
		},
		/**
		 * 根据id判断用户的信息是否已读
		 * @DateTime 2020-03-05T13:58:25+0800
		 * @param    {[type]}                 id [description]
		 * @return   {[type]}                    [description]
		 */
		getUserChatOne(id) {
			/*选择当前时，阻止多次请求*/
			if (this.currentUserId === id && this.userChatList.length > 1) {return }

			this.userChatList.forEach(function(item, i) {
				if (item.send_id == id) {
					item.read_data = '已读'
					return;
				}
			})
			let success = (res => {		
				this.userChatMessage = res.data;
				this.currentUserId = id;
				let message = JSON.stringify({
					type: 'allread',
					send_id: this.currentUserId,
					receive_id:  this.$g.user_id
				})
				this.ws.send(message)
				this.someMethod()
			})
			this.$ajax({
				url: '/api/user/user_chat',
				params: {
					sr_1: id,
					sr_2:  this.$g.user_id,
					update_read: 1,
					orderby:'time',
					orderby_desc:'asc',
					server_ip: location.hostname
				},
				func:{success:success}
			})
		},
		/**
		 * websocket 通讯
		 * @DateTime 2020-03-05T13:59:38+0800
		 * @return   {[type]}                 [description]
		 */
		websocket() {
			let webSocketChatURL = sessionStorage.getItem('user_chat_url');
			let serverIp = sessionStorage.getItem('host_addr').substring(7,24)
			this.ws = new WebSocket(webSocketChatURL)
			this.ws.onopen = () => {

				var message = JSON.stringify({
					type: 'login',
					uid: this.$g.user_id,
					server_ip:  serverIp
				})
				this.ws.send(message)
				// Web Socket 已连接上，使用 send() 方法发送数据
				console.log('已连接上...,发送身份信息：' + message)
			}
		
			this.ws.onmessage = (evt => {
				var data = JSON.parse(evt.data);
				if (data.status == 'success') {
					var type = data.type
					var data = data.data
					var flag = false;

					// console.log(data[0].send_id, data[0].receive_id, this.currentUserId, type);
					if (type == 'send') {
						if (data[0].receive_id == this.currentUserId) { // 当前聊天用户，直接追加数组
							this.userChatMessage.push(data[0])
						}
						this.userChatList.forEach(function(item, i) {
							if (item.send_id == data[0].receive_id) {
								item.content = data[0].content;
								flag = true;
								return;
							}

						})
					} else if (type == 'receive') {

						if (data[0].send_id == this.currentUserId) { // 当前聊天用户，直接追加数组
							this.userChatMessage.push(data[0])
						}
						var _this = this;
						this.userChatList.forEach(function(item, i) {
							if (item.send_id == data[0].send_id) {
								item.content = data[0].content
								if( item.send_id == _this.currentUserId ){
									item.read_data = '已读'
									_this.getUserChatOne(data[0].send_id)
								}else{
									item.read_data = '未读'
								}
								
								flag = true;
								return;
							}
						});

						let message = JSON.stringify({
							type: 'read',
							message_id: data[0].id
						})
						this.ws.send(message)

					} else {
						flag = true;
					}

					this.someMethod()

					if (!flag) {

						this.userChatList.unshift({
							avatar_path: data[0].send_avatar_path,
							content: data[0].content,
							create_time: data[0].create_time,
							//read_data : "未读",
							receive_id: data[0].receive_id,
							send_id: data[0].send_id,
							//sum_data : 26,
							time: data[0].create_time,
							username: data[0].send_name
						})
					}
					// this.EmojiUrl(2)
				}else if (data.status == 'error') {
					return this.$message.error(data.data)
				}


				// console.log('数据已接收...:', data)
			})
			this.ws.onclose = function() {
				// 关闭 websocket
				console.log('连接已关闭...')
			}
			// 组件销毁时调用，中断websocket链接
			this.over = () => {
				this.ws.close()
			}
		},
		/**
		 * 提交消息
		 * @DateTime 2020-03-05T13:49:34+0800
		 * @return   {[type]}                 [description]
		 */
		sendMessage() {
			let imgArr = document.querySelectorAll('.w-e-text img')
			let len = this.editor.txt.text().replace(/&nbsp;/g, '').replace(/^\s+|\s+$/g, '')
			if (imgArr.length == 0 &&  len.length ==  0 ) {
				return this.$message.warning('输入框不能为空');
			}
            let editorHtml=this.editor.txt.html().replace(/<br\s*[\/]?>/gi, '');//去除html里面的</br>
			let message = JSON.stringify({
				type: 'say',
				to_client_id: this.currentUserId,
				content: editorHtml
			})
			this.ws.send(message)
			console.log('发送数据...:', message)
			this.chatInput = ''
			this.editor.txt.clear()
			this.editor.menus.menus.link._active = false
		

		}
	}
}
</script>
<style type="text/css">
.my-scrollbar {
	height: 100%;
}
</style>